// 云函数入口文件
const cloud = require("wx-server-sdk");
const OSS = require("ali-oss");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

// 创建OSS客户端
function createOssClient() {
  const accessKeyId = process.env.ALIYUN_ACCESS_KEY_ID;
  const accessKeySecret = process.env.ALIYUN_ACCESS_KEY_SECRET;
  const bucket = process.env.OSS_BUCKET_NAME || "srs-ocr";
  const region = process.env.OSS_REGION || "oss-cn-guangzhou";

  if (!accessKeyId || !accessKeySecret) {
    throw new Error("缺少阿里云访问密钥配置");
  }

  return new OSS({
    region: region,
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    bucket: bucket,
    secure: true,
    timeout: 60000,
  });
}

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { fileContent, fileName } = event;

    if (!fileContent) {
      return {
        code: 400,
        message: "缺少文件内容",
        data: null,
      };
    }

    // 创建OSS客户端
    const client = createOssClient();

    // 生成唯一文件名
    const timestamp = new Date().getTime();
    const fileExtension = fileName.split(".").pop() || "jpg";
    const ossKey = `uploads/${timestamp}_${fileName}`;

    // 将base64转换为Buffer
    const buffer = Buffer.from(fileContent, "base64");

    // 上传到OSS，设置公共读权限
    const result = await client.put(ossKey, buffer, {
      headers: {
        "x-oss-object-acl": "public-read",
      },
    });

    return {
      code: 0,
      message: "上传成功",
      data: {
        url: result.url,
        key: ossKey,
        size: buffer.length,
      },
    };
  } catch (error) {
    console.error("文件上传错误:", error);
    return {
      code: 500,
      message: `上传失败: ${error.message}`,
      data: null,
    };
  }
};
